import java.util.LinkedList;
import java.util.NoSuchElementException;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;

import codeg.CodeGeneration;
import codeg.CodeGenerationContext;
import codeg.Codeg;
import codeg.CodegException;


@XmlRootElement
public class MatrixCodeg extends Codeg {
    @XmlElement(name = "row")
    public TableContent content = new TableContent(3, 3);

    @Override
    public CodeGeneration getCode(CodeGenerationContext context)
        throws CodegException {
        CodeGeneration code = new CodeGeneration(this);

        /* This codeg only generates Java code currently */
        if (context.getLanguage() != CodeGenerationContext.LANGUAGE.JAVA) return code;

        String s = "new int[][] { ";
        for (int i = 0; i < content.get_rows(); i++) {
            s += "{";
            for (int j = 0; j < content.get_cols(); j++) {
                s += content.get_value(i, j) + ", ";
            }
            s = s.subSequence(0, s.length() - 2) + "}, ";
        }
        s = (String) s.subSequence(0, s.length() - 2);
        s += " }";
        code.setLocalCode(s);

        return code;
    }
}

// A dummy class that maps the array list to an attribute and gives it a pretty
// name
class Row extends LinkedList<Integer> {
    private static final long serialVersionUID = -4836004357157631440L;
    @XmlElement(name = "cell")
    public LinkedList<Integer> content = this;
}


class TableContent extends LinkedList<Row> {
    private static final long serialVersionUID = -1481014564806241782L;

    public LinkedList<Row> rows = this;

    public TableContent(int n_rows, int n_cols) {
        for (int i = 0; i < n_rows; i++) {
            Row l = new Row();
            for (int j = 0; j < n_cols; j++)
                l.add(0);
            add(l);
        }
    }

    public int get_rows() {
        return size();
    }

    public int get_cols() {
        return getLast().size();
    }

    public void new_row() {
        Row l = new Row();
        for (int i = 0; i < get_cols(); i++)
            l.add(0);
        add(l);
    }

    public void del_row() {
        try {
            removeLast();
        }
        catch (NoSuchElementException e) {}
    }

    public void new_col() {
        for (int i = 0; i < get_rows(); i++)
            get(i).add(0);
    }

    public void del_col() {
        try {
            for (int i = 0; i < get_rows(); i++)
                get(i).removeLast();
        }
        catch (NoSuchElementException e) {}
    }

    public int get_value(int r, int c) {
        return get(r).get(c);
    }

    public void set_value(int r, int c, int value) {
        get(r).set(c, value);
    }

    public void clear() {
        super.clear();
    }
}